const app = getApp()

const regeneratorRuntime  =require("../../utils/regeneratorRuntime.js")
const promisify = require('../../utils/promisify.js');
import { $wuxActionSheet } from '../../dist/index'

Page({
  data: {
    statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],
    isIphoneX: app.globalData.isIphoneX,
    isIphone: app.globalData.isIphone,
    store_detail:{
      store_name:'复美大药房',
      store_address:'上海市浦东新区碧波路690号',
      store_manager: 'QWE',
      begin_time: "",
    },
    left_time: {day: 0, hour: 0, min: 0, sec: 0},
    isStoreUnfold: false,
    isShowCustomCamera: false,
    cameraInsertData: null,
    currentImage: '',

    task:{
      missions:[
        {
          corp_id: "ww12f1a59f5e6291f2",
          isDone: false,
          is_show: true,
          mission_begin_time: "2020-02-09",
          mission_description: null,
          mission_end_time: "2020-08-31",
          mission_id: 250,
          mission_is_must: true,
          mission_name: "战疫物资库存统计",
          mission_questions:[
            {
              question_index: 1,
              question_option: null,
              question_title: "请填写口罩库存量，单位「件」",
              question_type: "数值",
            },
            {
              question_index: 2,
              question_option: null,
              question_title: "请填写酒精库存量，单位「件」",
              question_type: "数值",
            },
            {
              question_index: 3,
              question_option: null,
              question_title: "请填写泡腾片库存量，单位「件」",
              question_type: "数值",
            },
          ],
          mission_status: true,
          mission_types: "自定义",
        },
        {
          corp_id: "ww12f1a59f5e6291f2",
          isDone: false,
          is_show: false,
          mission_begin_time: "2020-02-03",
          mission_description: null,
          mission_end_time: "2020-05-31",
          mission_id: 295,
          mission_is_must: false,
          mission_name: "战疫物资库存统计(货架采集)",
          mission_questions:[
            {
              description: "",
              question_index: 1,
              question_option: null,
              question_title: "库存拍照",
              question_type: "拍照",
            }
          ],
          mission_status: true,
          mission_types: "自定义",
        },
        {
          corp_id: "ww12f1a59f5e6291f2",
          isDone: false,
          is_show: false,
          mission_begin_time: "2020-02-03",
          mission_description: "填写商品库存量、订货量，单位「件」（此任务自动关联巡店员拓店，管理员可在后台修改任务描述，修改关联门店）",
          mission_end_time: "2020-05-31",
          mission_id: 27,
          mission_is_must: false,
          mission_name: "库存、订货统计",
          mission_questions:[
            {
              question_index: 1,
              question_option: ["已付全款", "已付定金", "货到付款"],
              question_title: "付款状态",
              question_type: "单选",
            },
            {
              question_index: 2,
              question_title: "库存拍照",
              question_type: "拍照",
            },
            {
              question_index: 3,
              question_title: "订货量",
              question_type: "数值",
            },
            {
              question_index: 4,
              question_title: "付款状态",
              question_type: "单行文本",
            },
            {
              question_index: 5,
              question_title: "备注",
              question_type: "多行文本",
            },
          ],
          mission_status: true,
          mission_types: "自定义",
        },
      ],
    }
    
  },
  onLoad: function () {
    var now = new Date();
    var year = now.getFullYear(); //得到年份
    var month = now.getMonth();//得到月份
    var date = now.getDate();//得到日期
    var day = now.getDay();//得到周几
    var hour = now.getHours();//得到小时
    var min = now.getMinutes();//得到分钟
    var sec = now.getSeconds();//得到秒
    month = month + 1;
    if (month < 10) month = "0" + month;
    if (date < 10) date = "0" + date;
    if (hour < 10) hour = "0" + hour;
    if (min < 10) min = "0" + min;
    if (sec < 10) sec = "0" + sec;
   
    
    this.data.store_detail['begin_time'] = year+'-'+month+'-'+date+' '+hour+':'+min+':'+sec
    this.setData({
      store_detail: this.data.store_detail
    })

    wx.setNavigationBarTitle({
      title: '巡店任务',
    })
    
    app.globalData.store_detail = this.data.store_detail
    app.globalData.store_detail['task'] = this.data.task

    this.storeTimeAutoAdd()
  },

  storeTimeAutoAdd() {
    const timer = setInterval(() => {
      const { min = 0, sec = 0 } = this.data.left_time
      const seconds = parseInt(min) * 60 + parseInt(sec) + 1
      const _min = Math.floor(seconds / 60), _sec = seconds % 60, left_time = this.data.left_time
      left_time.min = _min < 10 ? '0' + _min : _min
      left_time.sec = _sec < 10 ? '0' + _sec : _sec
      this.setData({ left_time })
    }, 1000)
    this.data.autoAddTimer = timer
  },

  toggleStoreHeader() {
    const { isStoreUnfold } = this.data
    this.setData({
      isStoreUnfold: !isStoreUnfold
    })
  },

  // 选择打开的门店任务
  onClick: function (e) {
    console.log(e)
    var idx = e.currentTarget.dataset.index
    var missions = this.data['task'].missions
    for (let i = 0; i < missions.length; i++) {
      console.log(i == idx && missions[idx]['is_show'] == false)
      if (i == idx && missions[idx]['is_show'] == false) {
        missions[i]['is_show'] = true
        console.log(idx, missions)
      } else {
        missions[i]['is_show'] = false
        console.log(idx, missions)
      }
    }

    app.globalData.store_detail['task']['missions'] = missions
    this.setData({
      task: app.globalData.store_detail['task'],
      openTask: idx,
    })
    console.log
  },

  submitData() {
    wx.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 1500
    })
  },

  checkMissionIsDone(missions, that) {
    // console.log('---------missions: ', missions)
    missions.map(m => {
      const done_arr = []
      m.mission_questions.map(q => {
        if(q.image_list) {
          done_arr.push(Boolean(q.answer || q.image_list.length > 0 || q.remark))
        }
      })
      if(m.mission_questions && done_arr.filter(item => item).length === m.mission_questions.length ) {
        m.isDone = true
      } else {
        m.isDone = false
      }
    })
    that.setData({ ['task.missions']: missions})
  },


  // 巡店任务文本题
  mission_text: function (e) {
    console.log(e.detail.value)
    console.log(e.currentTarget.dataset)
    var missionData = e.currentTarget.dataset.missiondata
    var outside_index = e.currentTarget.dataset.outsideindex
    var idx = e.currentTarget.dataset.index

    var InsertData = {}
    InsertData = {
      "image_list": [],
      "question_option": null,
      "question_index": missionData.mission_questions[idx]['question_index'],
      "question_title": missionData.mission_questions[idx]['question_title'],
      "question_type": missionData.mission_questions[idx]['question_type'],
    }
    if (missionData.mission_questions[idx]['question_type'] === '数值') {
      InsertData['answer'] = e.detail.value
    } else {
      InsertData['remark'] = e.detail.value
    }
    console.log('InsertData', InsertData)

    app.globalData.store_detail['task']['missions'][outside_index]['mission_questions'][idx] = InsertData
    this.setData({
      task: app.globalData.store_detail['task']
    })
    this.checkMissionIsDone(this.data.task.missions, this)
    console.log(this.data.task)
  },

  // 巡店任务单选题
  mission_radio: function (e) {
    console.log(e.currentTarget.dataset)
    var missionData = e.currentTarget.dataset.missiondata
    var outside_index = e.currentTarget.dataset.outsideindex
    var idx = e.currentTarget.dataset.index
    var image_list = []
    image_list.push(parseInt(e.detail.value))

    var InsertData = {}
    InsertData = {
      "question_index": missionData.mission_questions[idx]['question_index'],
      "question_title": missionData.mission_questions[idx]['question_title'],
      "question_type": missionData.mission_questions[idx]['question_type'],
      "question_option": missionData.mission_questions[idx]['question_option'],
      "answer": missionData.mission_questions[idx]['question_option'][e.detail.value],
      "image_list": image_list,
    }

    console.log('InsertData', InsertData)

    app.globalData.store_detail['task']['missions'][outside_index]['mission_questions'][idx] = InsertData

    this.setData({
      task: app.globalData.store_detail['task']
    })
    this.checkMissionIsDone(this.data.task.missions, this)
    console.log(this.data.task)
  },

  onMultiChoose: function (e) {
    this.setData({
      on_multi_choose: true,
    })
    console.log(e.currentTarget.dataset)

    app.globalData.missionData = e.currentTarget.dataset.missiondata
    app.globalData.outside_index = e.currentTarget.dataset.outsideindex
    app.globalData.idx = e.currentTarget.dataset.index

    wx.navigateTo({
      url: './multi-choose/multi-choose'
    })
  },

  addPhoto(e) {
    const that = this
    var missionData = e.currentTarget.dataset.missiondata
    var outside_index = e.currentTarget.dataset.outsideindex
    var idx = e.currentTarget.dataset.index
    if (missionData.mission_questions[idx]['image_list'] == undefined) {
      missionData.mission_questions[idx]['image_list'] = []
    }
    var InsertData = {}

    InsertData = {
      "store_id": this.data.storeId,
      "mission_id": missionData.mission_id,
      "visit_id": this.data.visit_id,
      "question_index": missionData.mission_questions[idx]['question_index'],
      "question_title": missionData.mission_questions[idx]['question_title'],
      "question_type": "拍照",
      "image_list": missionData.mission_questions[idx]['image_list'],
    }
    console.log('InsertData', InsertData)
    this.data.cameraInsertData = {...InsertData, outside_index, idx}

    const hide = $wuxActionSheet().showSheet({
      theme: 'wx',
      // titleText: '请正握手机，正对货架进行陈列拍照',
      buttons: [{
              text: '拍摄照片并上传'
          },
          {
              text: '拍摄照片至相册'
          },
          // {
          //     text: '从相册选择照片'
          // },
      ],
      async buttonClicked(index, item) {
        if(index === 0) {
          that.mission_camera({ type: 'upload' })
        } else if( index === 1 ) {
          that.mission_camera({ type: 'save' })
        }
        else if (index === 2) {
          that.chooseImageFromAlbum({ InsertData, that, hide, outside_index, idx })
        }
        return true
      }
    })
  },

  // 打开巡店任务相机
  mission_camera: function ({ type }) {
    this.setData({
      // isShowCustomCamera: true,
    })
    this.data.canTakePhoto = true
    this.data.custom_camera_type = type
    this.onCustomCamera()
  },

  onCustomCamera(e) {
    const that = this
    let { cameraInsertData:InsertData, custom_camera_type, canTakePhoto } = that.data
    if(!canTakePhoto) {
      return
    }
    const ctx = wx.createCameraContext()
    const { outside_index, idx } = InsertData
    delete InsertData.outside_index
    delete InsertData.idx
    const { isIphone } = app.globalData

    // ctx.takePhoto({
    //   quality: 'high',
    wx.chooseImage({
      count: 1,
      sizeType: ['original'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        if(custom_camera_type == 'save') {
          that.setData({
            currentImage: res.tempFilePaths[0]
            // currentImage: res.tempImagePath
          })
        }
        const tempFilePaths = res.tempFilePaths[0]
        // const tempFilePaths = res.tempImagePath
        // console.log('tempFilePaths: ', tempFilePaths)
        // 防止一次自定义相机多次点击拍照
        that.data.canTakePhoto = false
        // iPhone拍出来的图片尺寸会过大，需要压缩
        if(!isIphone) {
          that.addWaterMark({ tempImagePath:tempFilePaths, InsertData, that, outside_index, idx, custom_camera_type })
        } else {
          wx.compressImage({
            src: tempFilePaths, // 图片路径
            quality: 80, // 压缩质量
            success(res) {
              that.addWaterMark({ tempImagePath:res.tempFilePath, InsertData, that, outside_index, idx, custom_camera_type })
            }
          })
        }
      }
    })
  },

  async addWaterMark({ tempImagePath, custom_camera_type, that, InsertData,  outside_index, idx  }) {
    if(custom_camera_type === 'save') {
      wx.saveImageToPhotosAlbum({
        filePath: tempImagePath,
        success(res) {
          wx.showToast({
            title: '保存成功',
            mask: true,
            success() {
              setTimeout(()=>{
                that.setData({
                  isShowCustomCamera: false,
                  currentImage: null
                })
                that.data.canTakePhoto = true
              }, 1000)
            }
          })
          // console.log('saveImageToPhotosAlbum res:', res)
        }
      })
    } else if (custom_camera_type === 'upload') {
      if(!app.globalData.store_detail['task']['missions'][outside_index]['mission_questions'][idx]['image_list']){
        app.globalData.store_detail['task']['missions'][outside_index]['mission_questions'][idx]['image_list'] = []
      }
      var item = {'image_url':tempImagePath}
      app.globalData.store_detail['task']['missions'][outside_index]['mission_questions'][idx]['image_list'].push(item)
      this.setData({
        task: app.globalData.store_detail['task']
      })
      this.checkMissionIsDone(this.data.task.missions, this)
      console.log(app.globalData.store_detail['task']['missions'][outside_index]['mission_questions'][idx]['image_list'])

    }
  },

  customCameraError(e){
    console.log('e: ', e)
  },

  closeCustomCamera() {
    this.setData({
      isShowCustomCamera: false
    })
  },
})
